<?php
namespace Topxia\Service\Qiniu\Impl;

require 'qiniu/autoload.php';

use Topxia\Service\Common\BaseService;
use Topxia\Service\Qiniu\QiniuService;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Symfony\Component\Form\Exception\RuntimeException;

class QiniuServiceImpl extends BaseService implements QiniuService
{   
    private $accessKey = '2sdFTHpdzDVoT2N9S-OVUGA0A4mlzcujL3mcmCkq';
    private $secretKey = 'S_Xcd59O8N--0ooG995_QuPfBpKAiJejvhy7GnUV';
    private $bucket = 'baqianwei';

    public function initQiniu($targetPath,$filename)
    {   
        //throw new RuntimeException(print_r($targetPath)); 
        $this->Qiniu($targetPath,$filename);
        //throw new RuntimeException("Error Processing Request");  
        return 'debug';
    }

    public function addQiniuFile($targetType, $targetId, $qiniuname, $originalFile)
    {
        //$file = $this->getFileImplementor('qiniu')->addFile($targetType,$targetId,$originalFile);
        //封装数据库
        $uploadFile = array();
        $uploadFile['storage'] = 'local';
        $uploadFile['targetId'] = $targetId;
        $uploadFile['targetType'] = $targetType;
        $time = time();
        $filename = $time.'-'.$originalFile['name'];
        $uploadFile['filename'] = $originalFile['name'];
        $uploadFile['qiniu_name'] = $qiniuname;
        $retval="";  
        $pt=strrpos($filename, ".");  
        if ($pt) $retval=substr($filename, $pt+1, strlen($filename) - $pt); 
        $uploadFile['ext'] =  $retval;
        $uploadFile['size'] = $originalFile['size'];
        $uploadFile['hashId'] = "{$uploadFile['targetType']}/{$uploadFile['targetId']}/{$filename}";
        $uploadFile['convertHash'] = "ch-{$uploadFile['hashId']}";
        $uploadFile['type'] = 'video';
        $uploadFile['updatedUserId'] = $uploadFile['createdUserId'] = $this->getCurrentUser()->id;
        $uploadFile['updatedTime'] = $uploadFile['createdTime'] = $time;
        $file = $this->getUploadFileDao()->addFile($uploadFile);

        return $file;
    }

    public function getUptoken($basename)
    {
        $accessKey = $this->accessKey;
        $secretKey = $this->secretKey;
        $auth = new Auth($accessKey, $secretKey);
        $bucket = $this->bucket;
        //$basename = basename($filename);

        //配置预转持久化结果的保存空间和文件名
        $entry = 'baqianwei-video:'.$basename.'.mp4';
        $encodeEntryURI = \Qiniu\base64_urlSafeEncode($entry);

        //使用persistantOps模式

        //水印文字
        $text = '八千味';
        $encodeText = \Qiniu\base64_urlSafeEncode($text);

        //有水印（八千味）
        //$pfop = "avthumb/mp4/wmText/".$encodeText."/wmGravityText/SouthEast/wmFontSize20"."|saveas/".$encodeEntryURI;

        //无水印
        $pfop = "avthumb/mp4|saveas/".$encodeEntryURI;

        //转码完成后回调到业务服务器。（公网可以访问，并相应200 OK）
        $notifyUrl = '';

        //独立的转码队列：https://portal.qiniu.com/mps/pipeline
        $pipeline = 'abc';

        $policy = array(
            'insertOnly' => 1,
            'persistentOps' => $pfop,
            'persistentNotifyUrl' => $notifyUrl,
            'persistentPipeline' => $pipeline
        );

        // 生成上传 Token
        $token = $auth->uploadToken($bucket,null,3600,$policy);

        return $token;
    }

    protected function Qiniu($targetPath,$filename)
    {
    $accessKey = $this->accessKey;
    $secretKey = $this->secretKey;
    $auth = new Auth($accessKey, $secretKey);

    $bucket = $this->bucket;

    $basename = basename($filename);

    //配置预转持久化结果的保存空间和文件名
    $entry = 'baqianwei-video:'.$basename.'.mp4';
    $encodeEntryURI = \Qiniu\base64_urlSafeEncode($entry);

    //使用persistantOps模式

    //水印文字
    $text = '八千味';
    $encodeText = \Qiniu\base64_urlSafeEncode($text);

    $pfop = "avthumb/mp4/wmText/".$encodeText."/wmGravityText/SouthEast/wmFontSize20"."|saveas/".$encodeEntryURI;

    //转码完成后回调到业务服务器。（公网可以访问，并相应200 OK）
    $notifyUrl = '';

    //独立的转码队列：https://portal.qiniu.com/mps/pipeline
    $pipeline = 'abc';

    $policy = array(
        'saveKey'=>$basename,
        'persistentOps' => $pfop,
        'persistentNotifyUrl' => $notifyUrl,
        'persistentPipeline' => $pipeline
    );

    // 生成上传 Token
    $token = $auth->uploadToken($bucket,null,3600,$policy);

    // 要上传文件的本地路径
    //$filePath = $targetPath.'/'.$filename;//$uploadFile['tmp_name'];//'../LOGO.wmv';
    // 上传到七牛后保存的文件名
    //$key = $filename;
    // 初始化 UploadManager 对象并进行文件的上传。
    $uploadMgr = new UploadManager();

    list($ret, $err) = $uploadMgr->putFile($token);
    echo "\n====> putFile result: \n";
    if ($err !== null) {
        var_dump($err);
        //var_dump($uploadFile);
    } else {
        var_dump($ret);
    }
    }

    protected function getUploadFileDao()
    {
        return $this->createDao('File.UploadFileDao');
    }
}